
package ru.st.selenium;

/**
 * @author Aleksandr Tsuranov
 *
 */

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.testng.*;
import org.testng.annotations.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class AddRemoveFilm extends ru.st.selenium.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Test
  public void testAddRemoveFilm() throws Exception {
    
	// LOGIN 
    driver.get(baseUrl + "/php4dvd/");
    driver.findElement(By.id("username")).clear();
    driver.findElement(By.id("username")).sendKeys("admin");
    driver.findElement(By.name("password")).clear();
    driver.findElement(By.name("password")).sendKeys("admin");
    driver.findElement(By.name("submit")).click();
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.id("results"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }	  
	  
	// ADD FILM WITH WRONG DATA (NEGATIVE TEST 1)
	driver.get(baseUrl + "/php4dvd/");
    driver.findElement(By.xpath(".//*[@id='content']/section/nav/ul//a[@href='./?go=add']")).click();
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.name("name"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }
    // 	leave obligatory "name" field empty and submit form
    driver.findElement(By.name("year")).clear();
    driver.findElement(By.name("year")).sendKeys("2013");
    driver.findElement(By.id("submit")).click();
    
    // verify that error message was displayed    
    assertTrue(isElementPresent(By.xpath(".//*[@id='updateform']/table/tbody//td[2]/input[@name='name'][@class='required error']")));
    assertEquals("This field is required", driver.findElement(By.cssSelector("label[for='name'][class='error']")).getText());
    
 // ADD FILM WITH WRONG DATA (NEGATIVE TEST 2)
    driver.get(baseUrl + "/php4dvd/");
    driver.findElement(By.xpath(".//*[@id='content']/section/nav/ul//a[@href='./?go=add']")).click();
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.name("name"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

    // leave obligatory "year" field empty and submit form
    driver.findElement(By.name("name")).clear();
    driver.findElement(By.name("name")).sendKeys("Alex Great Film");
    driver.findElement(By.id("submit")).click();
    
    // verify that error message was displayed
    assertTrue(isElementPresent(By.xpath(".//*[@id='updateform']/table/tbody//td[2]/input[@name='year'][@class='required digits error']")));
    assertEquals("This field is required", driver.findElement(By.cssSelector("label[for='year'][class='error']")).getText());
    
 // ADD FILM WITH CORRECT DATA (POSITIVE TEST)
    driver.get(baseUrl + "/php4dvd/");
    driver.findElement(By.xpath(".//*[@id='content']/section/nav/ul//a[@href='./?go=add']")).click();
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.name("name"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }
    
    // fill in form for new film and submit it
    driver.findElement(By.name("name")).clear();
    driver.findElement(By.name("name")).sendKeys("Alex Great Film");
    driver.findElement(By.name("year")).clear();
    driver.findElement(By.name("year")).sendKeys("2013");
    driver.findElement(By.name("aka")).clear();
    driver.findElement(By.name("aka")).sendKeys("Super movie about superman.");
    driver.findElement(By.name("duration")).clear();
    driver.findElement(By.name("duration")).sendKeys("120");
    driver.findElement(By.name("rating")).clear();
    driver.findElement(By.name("rating")).sendKeys("90");
    driver.findElement(By.id("own_no")).click();
    driver.findElement(By.id("cover")).sendKeys("c:\\alexfilmcover.jpg");
    driver.findElement(By.name("taglines")).clear();
    driver.findElement(By.name("taglines")).sendKeys("thriller, alex");
    driver.findElement(By.name("genres")).clear();
    driver.findElement(By.name("genres")).sendKeys("thriller");
    driver.findElement(By.id("submit")).click();
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.id("movie"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }
    
    // store newly added movie's address
    String movieAddress = driver.getCurrentUrl();
    
    // verify that movie was added successfully
    assertTrue(isElementPresent(By.xpath(".//*[@id='movie']//h2")));
    assertEquals("Alex Great Film (2013)", driver.findElement(By.xpath(".//*[@id='movie']//h2")).getText());
    
    // DELETE PREVIOUSLY ADDED MOVIE
    driver.get(movieAddress);
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.xpath(".//*[@id='content']/section/nav/ul//div/div/a[contains(@onclick,'./?go=delete&id=')]"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

    driver.findElement(By.xpath(".//*[@id='content']/section/nav/ul//div/div/a[contains(@onclick,'./?go=delete&id=')]")).click();
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isAlertPresent()) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

    assertTrue(closeAlertAndGetItsText().matches("^[\\s\\S]*$"));
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.id("results"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

    // verify that movie was deleted successfully (movie's link is not present on the page)
    assertFalse(isElementPresent(By.xpath(".//*a[@href='"+movieAddress+"']")));
    //System.out.println(".//*a[@href='"+movieAddress+"']");
  }

  private boolean isAlertPresent() {
    try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        return true;
      } catch (NoAlertPresentException e) {
    	  return false;  	
      }
}

private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}

